<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小球重力</title>
</head>
<body>
<canvas id="canvas" style="border: 1px solid gray;">当前浏览器不支持,请更换浏览器重试</canvas>
</body>
<script>
    var CANVAS_WIDTH = 1024;
    var CANVAS_HEIGHT = 768;
    window.onload = function () {
        var canvas = document.getElementById("canvas");
        var content = canvas.getContext('2d');
        canvas.width =CANVAS_WIDTH;
        canvas.height = CANVAS_HEIGHT;
        setInterval(function(){
            render(content);
            update();
        },16.7);
    }
    var ball = {x:500,y:200,r:20,g:2,vx:-2,vy:-1,color:"#005588"};
    function render(cxt) {
        cxt.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
        cxt.beginPath();
        cxt.arc(ball.x,ball.y,ball.r,0,2*Math.PI);
        cxt.fillStyle = ball.color;
        cxt.fill();
    }

    function update() {
        ball.x += ball.vx;
        ball.y += ball.vy;
        ball.vy += ball.g;
        if(ball.y>= CANVAS_HEIGHT - ball.r){
            ball.y = CANVAS_HEIGHT - ball.r;
            ball.vy = -ball.vy*0.7;
        }
        if(ball.y <= ball.r){
            ball.y = ball.r;
            ball.vy = -ball.vy*0.8;
        }
    }
</script>
</html>